<template>
  <div>
    <a-row :gutter="12">
      <a-col :span="6">
        <a-card :bordered="false" title="分组列表">
          <a-tooltip title='排版模式下，可通过拖拽分组实现快速排序。' slot="extra" v-if="hasPerm('scriptTree:edit')">
            <a-switch
              :checked="draggable"
              @change="setDraggable"
              checkedChildren="排版"
              unCheckedChildren="浏览"/>
            <a-icon type="question-circle" style="margin-left: 8px;color: #999999"/>
          </a-tooltip>
          <a-dropdown
            :visible="visible"
            :trigger="['contextmenu']"
            @visibleChange="setVisible"
          >
            <a-menu slot="overlay" @click=setVisible(false) style="width: 150px">
              <a-menu-item key="0" @click="handleAdd('root')">
                <a-icon type="folder"/>
                新建根分组
              </a-menu-item>
              <a-menu-item key="1" @click="handleAdd">
                <a-icon type="folder-add"/>
                新建子分组
              </a-menu-item>
              <a-menu-item key="2" @click="handleAdd('edit')">
                <a-icon type="edit"/>
                重命名
              </a-menu-item>
              <a-menu-divider/>
              <a-menu-item key="3">
                <a-icon type="folder"/>
                添加至分组
              </a-menu-item>
              <a-menu-item key="4">
                <a-icon type="folder"/>
                移动至分组
              </a-menu-item>
              <a-menu-divider/>
              <a-menu-item key="5">
                <a-icon type="folder"/>
                删除主机
              </a-menu-item>
              <a-menu-item key="6" @click="handleRemove"><span style="color: red"><a-icon type="delete"/>删除此分组</span>
              </a-menu-item>
            </a-menu>
            <a-directory-tree
              :treeData="treeData"
              :draggable="draggable"
              @rightClick="handleRightClick"
              @select="handleClick"
              @drop="onDrop">
            </a-directory-tree>
          </a-dropdown>
        </a-card>
      </a-col>
      <a-col :span="18">
        <a-card :bordered="false">
          <s-table
            ref="table"
            :columns="columns"
            :data="loadData"
            :rowKey="(record) => record.id"
          >
            <template slot="operator">
              <a-row>
                <a-col :md="12" :sm="24">
                  <span class="table-title">脚本列表</span>
                </a-col>
                <a-col :md="12" :sm="24">
                  <div class="table-title-right" v-if="hasPerm('script:add')">
                    <a-button @click="$refs.Form.open()" icon="plus" type="primary">新增脚本</a-button>
                  </div>
                </a-col>
              </a-row>
            </template>
            <span slot="status" slot-scope="text">
                    <a-tag :color="text === 0 ? 'green' : text === 1 ? 'red' : text === 2 ? 'blue' : 'green'">
                        {{ text === 0 ? '成功' : text === 1 ? '失败' : text === 2 ? '构建中' : '未构建' }}
                    </a-tag>
                </span>

            <span slot="action" slot-scope="text, record">
                    <a v-if="hasPerm('script:exec')" @click="$refs.execForm.open(record)">{{
                        record.build_state === 2 ? '日志' : '执行'
                    }}</a>
                    <a-divider type="vertical" v-if="hasPerm('script:exec') & hasPerm('script:detail')"/>
                    <a v-if="hasPerm('script:detail')" @click="$refs.recordTable.open(record)">详情</a>
                    <a-divider
                      type="vertical"
                      v-if="hasPerm('script:detail') &
                            (hasPerm('script:edit') || hasPerm('script:clone') || hasPerm('script:delete'))
                        "
                    />
                    <a-dropdown v-if="hasPerm('script:edit') || hasPerm('script:clone') || hasPerm('script:delete')">
                        <a class="ant-dropdown-link"> 更多 <a-icon type="down"/> </a>
                        <a-menu slot="overlay">
                            <a-menu-item v-if="hasPerm('script:edit')">
                                <a v-if="hasPerm('script:edit')" @click="$refs.Form.open(record)">编辑</a>
                            </a-menu-item>
                            <a-menu-item v-if="hasPerm('script:clone')">
                                <a v-if="hasPerm('script:clone')" @click="$refs.Form.open(record, true)">克隆脚本</a>
                            </a-menu-item>
                            <a-menu-item v-if="hasPerm('script:delete')">
                                <a-popconfirm
                                  v-if="hasPerm('script:delete')"
                                  placement="topRight"
                                  title="确认删除？"
                                  @confirm="() => gameScriptDelete(record.id)"
                                >
                                    <a style="color: red">删除</a>
                                </a-popconfirm>
                            </a-menu-item>
                        </a-menu>
                    </a-dropdown>
                </span>
          </s-table>
          <s-form ref="Form" @ok="handleOk"/>
          <exec-form ref="execForm" @ok="handleOk"/>
          <record-table ref="recordTable"></record-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>
<script>
  import { STable } from '@/components'
  import sForm from './Form'
  import execForm from './ExecForm'
  import recordTable from './RecordTable'
  import * as api from '@/api/main/script'
  import * as groupApi from '@/api/main/ScriptGroup'

  export default {
    components: {
      STable,
      sForm,
      execForm,
      recordTable
    },
    data() {
      return {
        advanced: false,
        // 查询参数
        queryParam: { group: '34dd4665-a389-4387-bdca-0068e2529a65' },
        visible: false,
        draggable: false,
        treeData: [],
        groupForm: {
          name: '',
          parent: ''
        },
        group: {},
        bakTreeData: '',
        viewsTabs: [],
        // 表头
        columns: [
          {
            title: '脚本名称',
            dataIndex: 'name'
          },
          {
            title: '开始时间',
            dataIndex: 'build_at'
          },
          {
            title: '耗时',
            dataIndex: 'build_time'
          },
          {
            title: '上次构建状态',
            dataIndex: 'build_state',
            scopedSlots: { customRender: 'status' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {
          return api.getPage(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        timer: null
      }
    },
    created() {

      if (
        this.hasPerm('script:edit') ||
        this.hasPerm('script:delete') ||
        this.hasPerm('script:exec') ||
        this.hasPerm('script:detail') ||
        this.hasPerm('script:clone')
      ) {
        this.columns.push({
          title: '操作',
          width: '150',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        })
      }
      this.getGroupTree()
      this.initView()
      this.timer = window.setInterval(() => {
        setTimeout(this.$refs.table.refresh(), 0)
      }, 5000)
    },
    methods: {
      getGroupTree() {
        groupApi.getList(Object.assign(this.queryParam)).then(res => {
          this.treeData = res.data.data
          this.treeData = this.treeFilter(this.treeData, node => (this.hasPerm(node.title)))
        })
      },
      treeFilter(tree, func) {
        // 使用map复制一下节点，避免修改到原树
        return tree.map(node => ({ ...node })).filter(node => {
          node.children = node.children && this.treeFilter(node.children, func)
          return func(node) || (node.children && node.children.length)
        })
      },
      initView() {
        for (const item of this.viewsTabs) {
          if (this.hasPerm(item.view)) {
            if (!this.queryParam.view) {
              this.$message.error('没有可执行脚本权限,请联系管理员！')
              this.$router.push('/welcome')
            } else {
              this.queryParam.view = item.view
              this.$refs.table.refresh(true)
              return
            }
          }
        }
      },
      setVisible(checked) {
        this.visible = checked
      },
      handleRightClick(v) {
        if (this.hasPerm('script:edit')) {
          this.group = v.node
          this.setVisible(true)
        }
      },
      handleOk() {
        this.$refs.table.refresh()
      },
      setDraggable(checked) {
        this.draggable = checked
      },
      handleClick(e) {
        this.queryParam = {
          group: e.toString()
        }
        this.$refs.table.refresh()
      },
      handleRemove() {
        groupApi.deleteObj(this.group.value).then(res => {
          if (res.success) {
            this.$message.success('删除成功！')
            this.group = ''
            this.getGroupTree()
          } else {
            this.$message.error('删除失败' + res.message)
          }
        })
      },
      handleAdd(value) {
        if (value === 'root') {
          this.group = ''
          this.groupForm.parent = ''
        } else if (value === 'edit') {
          this.action = value
          this.groupForm.name = this.group.title
          this.groupForm.id = this.group.value
        } else {
          this.groupForm.parent = this.group.value
        }
        this.$confirm({
          title: this.action === 'edit' ? '重命名' : '添加脚本分组',
          icon: 'info-circle',
          content: this.addGroupForm,
          onOk: this.action === 'edit' ? this.editGroup : this.addGroup,
          onCancel() {
            console.log('Cancel')
          }
        })
      },
      addGroupForm() {
        return (
          <div>
            <a-form-item label="主机节点">
              <a-input v-model={this.groupForm.name}/>
            </a-form-item>
          </div>
        )
      },
      editGroup() {
        groupApi.updateObj({ id: this.groupForm.id, name: this.groupForm.name }).then(res => {
          if (res.success) {
            this.$message.success('重命名成功！')
          } else {
            this.$message.error('重命名失败' + res.message)
          }
          this.groupForm.name = ''
          this.action = ''
          this.getGroupTree()
        })
      },
      addGroup() {
        groupApi.addObj({ name: this.groupForm.name, parent: this.groupForm.parent }).then(res => {
          if (res.success) {
            this.$message.success('新增分组成功！')
          } else {
            this.$message.error('新增分组成功' + res.message)
          }
          this.groupForm.name = ''
          this.action = ''
          this.getGroupTree()
        })
      },
      onDrop(info) {
        const dropKey = info.node.eventKey // 目标的key
        const dragKey = info.dragNode.eventKey // 自己的key
        const dropPos = info.node.pos.split('-')
        const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
        const params = { id: dragKey, d_id: dropKey, action: dropPosition } // 传给后端参数
        groupApi.updatePartObj(params).then(res => {
          if (res.success) {
            this.getGroupTree()
          } else {
            return false
          }
        })
      },
      gameScriptDelete(id) {
        api.deleteObj(id).then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
            this.$refs.table.refresh(true)
          } else {
            this.$message.error('操作失败：' + res.message)
          }
        })
      }
    },
    beforeDestroy() {
      window.clearInterval(this.timer)
      this.timer = null
    }
  }
</script>
<style lang="less">
  button {
    margin-right: 8px;
  }

  .table-title-right {
    float: right;
    margin-right: 30px;
  }
</style>
